import { ref, computed, onMounted } from 'vue';
import { useWindowResize } from './useWindowResize';

export const useDeviceDetector = () => {
  // 设备类型
  const deviceType = ref<'mobile' | 'tablet' | 'pc'>('pc');
  // 窗口大小
  const { width } = useWindowResize();
  // 移动端阈值
  const MOBILE_WIDTH_THRESHOLD = 768;
  // 平板阈值
  const TABLET_WIDTH_THRESHOLD = 1024;

  // 通过User Agent检测设备类型
  const detectByUA = () => {
    let UA = '';
    if (import.meta.client) {
      UA = navigator.userAgent;
    } else {
      UA = useRequestHeader('user-agent') as string;
    }

    if (/(Android|webOS|iPhone|iPod|tablet|BlackBerry|Mobile)/i.test(UA)) {
      // 检测是否为平板
      if (/(iPad|Tablet|PlayBook|Silk)/i.test(UA)) {
        return 'tablet';
      }
      return 'mobile';
    }
    return 'pc';
  };

  // 通过窗口宽度检测设备类型
  const detectByWidth = () => {
    if (width.value === undefined) return 'pc';
    if (width.value < MOBILE_WIDTH_THRESHOLD) {
      return 'mobile';
    } else if (width.value < TABLET_WIDTH_THRESHOLD) {
      return 'tablet';
    } else {
      return 'pc';
    }
  };

  // 初始化检测
  deviceType.value = detectByUA();

  // 监听窗口大小变化，动态更新设备类型
  onMounted(() => {
    // 初始时根据窗口大小更新一次
    deviceType.value = detectByWidth();

    // 当窗口大小变化时更新
    const updateDeviceType = () => {
      deviceType.value = detectByWidth();
    };

    window.addEventListener('resize', updateDeviceType);

    // 清理监听器
    return () => {
      window.removeEventListener('resize', updateDeviceType);
    };
  });

  // 导出计算属性，方便使用
  const isMobile = computed(() => deviceType.value === 'mobile');
  const isTablet = computed(() => deviceType.value === 'tablet');
  const isPc = computed(() => deviceType.value === 'pc');

  return {
    deviceType,
    isMobile,
    isTablet,
    isPc,
    detectByUA,
    detectByWidth
  };
};